#include "DBManager.h"
#include "DBManager_p.h"

QVariantMap DBManagerPrivate::m_smapDatabaseInfo = QVariantMap();
QHash<Qt::HANDLE, DBManager*> DBManagerPrivate::m_shashInstances = QHash<Qt::HANDLE, DBManager*>();


DBManager::DBManager()
    : d(new DBManagerPrivate())
{

}

DBManager::~DBManager()
{
    delete d;
}

bool DBManager::addDatabase(const QVariantMap &databaseInfo)
{
    QString strDbName = databaseInfo.value("name").toString();
    if((strDbName.isEmpty())
            ||(DBManagerPrivate::m_smapDatabaseInfo.contains(strDbName)))
    {
        return false;
    }

    DBManagerPrivate::m_smapDatabaseInfo.insert(strDbName, databaseInfo);

    return true;
}

bool DBManager::contains(const QString &databaseName)
{
    QString strRealDbName = DBManagerPrivate::getDatabaseName(databaseName);

    if(QSqlDatabase::contains(strRealDbName))
    {
        return true;
    }

    QVariantMap dbInfo = DBManagerPrivate::m_smapDatabaseInfo.value(databaseName).toMap();
    if(dbInfo.isEmpty())
    {
        return false;
    }

    QString strType = dbInfo.value("type").toString();
    QString strDatabase = dbInfo.value("database").toString();

    if(strType.isEmpty()
            || strDatabase.isEmpty())
    {
        return false;
    }

    QSqlDatabase db = QSqlDatabase::addDatabase(strType, strRealDbName);
    db.setDatabaseName(strDatabase);
    QString strTmp = dbInfo.value("host").toString();
    if(!strTmp.isEmpty())
    {
        db.setHostName(strTmp);
    }
    strTmp = dbInfo.value("user").toString();
    if(!strTmp.isEmpty())
    {
        db.setUserName(strTmp);
    }
    strTmp = dbInfo.value("password").toString();
    if(!strTmp.isEmpty())
    {
        db.setPassword(strTmp);
    }

    if(0 == strType.compare("QMYSQL"))
    {
        db.setConnectOptions("MYSQL_OPT_RECONNECT=1");
    }
    if(!db.open())
    {
        if(0 == strType.compare("QMYSQL"))
        {
            db.setConnectOptions("");
        }
        return false;
    }

    return true;
}

QSqlDatabase DBManager::database(const QString &databaseName)
{
    if(!contains(databaseName))
    {
        return QSqlDatabase();
    }

    QString strRealDbName = DBManagerPrivate::getDatabaseName(databaseName);

    return QSqlDatabase::database(strRealDbName);
}

DBManagerPrivate::DBManagerPrivate()
{

}


QString DBManagerPrivate::getDatabaseName(const QString &databaseName)
{
    return QString("%1_%2")
            .arg(databaseName)
            .arg((quintptr)(QThread::currentThreadId()));
}
